# -*- coding: utf-8 -*-
# @Author: QX
# @File: YamlCaseParser.py
'''pip install PyYAML==6.0.1'''
import copy
import os
import uuid

import yaml

from core.globalContext import g_context
from utils.Generatestring import generate_unique_string


#读出单个YAML文件内容
def readYaml(filename):
    with open(filename,'r',encoding='utf-8')as f:
        data=yaml.full_load(f)
    return data

#第一次优化读出的yaml测试用例
def readYamlnew(filename):
    case_infos = []
    caseinfo = readYaml(filename)
    case_infos.append(caseinfo)
    return case_infos
#优化读出yaml文件的函数（传路径）----读出context.yaml中的内容并存到全局的dict中
def load_context_from_yaml(folder_path):#D:\Apirun2411\examples\yaml_testcase
    try:
        yaml_file_path=os.path.join(folder_path,'context.yaml')
        context = readYaml(yaml_file_path)
        g_context().set_by_dict(context)
        #新增一个account
        g_context().set_dict('account', generate_unique_string())

    except  Exception  as e:
        print(f"装载YAML文件失败：{str(e)}")

'''优化读出yaml文件的函数--读出指定目录下
的所有满足“数据_名称.yaml”这个条件的所有文件名，
组合成多个测试用例
'''
def load_yaml_files(folder_path):
    yaml_caseinfos = []
    # a.调用存储context.yaml的函数
    load_context_from_yaml(folder_path)
    # b.获得指定目录下的所有满足条件文件名
    file_names = []
    allfiles=os.listdir(folder_path)
    for f in allfiles:
        if f.endswith('.yaml')  and  f.split('_')[0].isdigit():
            file_number =  int(f.split('_')[0])
            file_names.append((file_number,f))
    file_names.sort()
    file_names = [f[-1]  for f in  file_names]
    #print(file_names)

    # c.组合文件路径并读出测试用例#D:\Apirun2411\examples\yaml_testcase\    yaml_00141login.yaml
    for file_name in file_names:
        file_path = os.path.join(folder_path,file_name)
        caseinfo =readYaml(file_path)
        #print(caseinfo)

        # d.把每个用例当成元素放到列表中
        yaml_caseinfos.append(caseinfo)
    return (yaml_caseinfos)

'''
统一一下格式，为后面的新增插件作为储备
获得满足条件文件夹的文件作为测试用例，多个文件
{
        "case_infos": case_infos,
        "case_names": case_names
    }
'''
def yaml_case_parser(folder_path):
    #1.定义放测试用例和测试名称的变量
    case_infos = []
    case_names = []
    #2.测试用例的来源
    yaml_caseinfos=load_yaml_files(folder_path)
    #3.遍历所有的测试用例，然后进统一格式的处理
    for caseinfo  in yaml_caseinfos:
        #1.先获得ddts
        ddts = caseinfo.get('ddts',[])
        if len(ddts)  > 0:
            caseinfo.pop('ddts')

        if len(ddts) ==0:
            case_name = caseinfo.get('desc', uuid.uuid4().__str__())
            caseinfo.update({"_case_name": case_name})
            case_infos.append(caseinfo)
            case_names.append(case_name)
        else:
            for ddt in ddts:
                new_case = copy.deepcopy(caseinfo)
                context = new_case.get('context', {})
                ddt.update(context)
                new_case.update({'context': ddt})
                #收集对应的测试用例的标题
                case_name = f'{caseinfo.get("desc", uuid.uuid4().__str__())}-{ddt.get("desc", uuid.uuid4().__str__())}'
                new_case.update({"_case_name": case_name})

                case_infos.append(new_case)
                case_names.append(case_name)


    return {
        "case_infos": case_infos,
        "case_names": case_names
    }


if __name__ == '__main__':

    folder_path='D:\Apirun2411\examples\debug_file'

    g=yaml_case_parser(folder_path)
    print(g)
